import { Observable, of, Subject } from "rxjs";
import { Injectable, Inject, OnInit } from "@angular/core";
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest
} from "@angular/common/http";
import { map, filter, tap } from "rxjs/operators";
import { HttpResponse } from "@angular/common/http";
import { Router } from "@angular/router";
import { environment } from "@environment/environment";

@Injectable()
export class NoopInterceptorService implements HttpInterceptor {
  constructor(
    private router: Router,
    @Inject("PendingService") private pendingService,
    @Inject("StoreService") private storeService,
    @Inject("Base64Service") private base64Service
  ) {
    this.init();
  }

  init() {
    this.addListen();
  }
  addListen() {
    // this.pending$.subscribe(e => {
    //   console.error(e, 999999);
    // });
  }
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const started = Date.now();
    const isI18n = new RegExp("assets/l10n/").test(req.url);

    this.pendingService.push(req.url);

    const url = isI18n
      ? `${environment.proto}${environment.host.www}${req.url}`
      : `${environment.proto}${environment.host.napi}${req.url}`;

    this.pendingService.set(true);

    const apiReq = req.clone({
      url: url,
      withCredentials: true,
      headers: req.headers.set("Authorization", "eh TOKEN")
    });

    return next.handle(apiReq).pipe(
      tap(
        event => {
          if (event instanceof HttpResponse) {
            const { code } = event.body;

            this.pendingService.pop();

            if (this.pendingService.isComplete()) {
              this.pendingService.set(false);
            }

            if (401 === code) {
              // do some thing
            }

            const elapsed = Date.now() - started;
          }
        },
        error => {
          console.error("NICE ERROR", error);
        }
      )
    );
  }
}
